package edu.langnan.xiaoli.controller.business;

import edu.langnan.xiaoli.base.AjaxResult;
import edu.langnan.xiaoli.base.controller.BaseController;
import edu.langnan.xiaoli.config.security.TokenService;
import edu.langnan.xiaoli.constant.XiaoLiConstants;
import edu.langnan.xiaoli.core.domain.LostDO;
import edu.langnan.xiaoli.core.dto.LostDTO;
import edu.langnan.xiaoli.core.dto.LostParamDTO;
import edu.langnan.xiaoli.core.page.TableDataInfo;
import edu.langnan.xiaoli.service.LostService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author cql
 */
@RestController
@RequestMapping("lost")
public class LostController extends BaseController {

    @Autowired
    private LostService lostService;

    @Autowired
    private TokenService tokenService;


    /***
     * 新增或修改 lost
     * @param param
     * @param request
     * @return
     */
    @PostMapping
    public AjaxResult saveOrUpdate(@RequestBody LostParamDTO param, HttpServletRequest request) {
        LostDO lost = new LostDO();

        BeanUtils.copyProperties(param, lost);

        // 图片
        StringBuilder sb = new StringBuilder();
        List<String> imgUrls = param.getImgUrls();
        for (String img : imgUrls) {
            sb.append(img + XiaoLiConstants.SEPARATOR);
        }

        lost.setImgs(sb.toString().trim());

        Integer stuId = tokenService.getLoginUser(request).getId();
        lost.setStuId(stuId);
        lostService.saveOrUpdate(lost);
        return AjaxResult.success();
    }


    /**
     * 查找登录用户的失物招领/寻物启事
     *
     * @param lostType 类型: 失物招领/寻物启事
     * @param status   状态："": 查找所有; "0":未完成; "1":已完成
     * @param request
     * @return
     */
    @GetMapping("list")
    public TableDataInfo lostList(@RequestParam(value = "lostType", defaultValue = "0") String lostType,
                                  @RequestParam(value = "status", defaultValue = "") String status,
                                  HttpServletRequest request) {
        Integer id = tokenService.getLoginUser(request).getId();
        // 分页
        startPage();
        List<LostDTO> result = lostService.findLostList(lostType, status, id);
        return getDataTable(result);
    }


}
